package com.base.jdbc;

import java.sql.*;

/**
 * @Description:
 * @author: May
 * @date: 2021/4/22
 */
public class JdbcForPG {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        // 参数：
        // jdbc协议:postgresql子协议://主机地址:数据库端口号/要连接的数据库名
        String url = "jdbc:postgresql://172.16.1.1:5432/db_test";
        // 数据库用户名
        String user = "postgres";
        // 数据库密码
        String password = "123";

        // 1. 加载Driver类，Driver类对象将自动被注册到DriverManager类中
        Class.forName("org.postgresql.Driver");

        // 2. 连接数据库，返回连接对象
        Connection conn = DriverManager.getConnection(url, user, password);

        String sql = "select *\n" +
                "from yw_person_info_collected where person_name like '%吴%'";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1,"测试");
        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            System.out.println("resultSet = " + resultSet.getString(2) + "," +
                    resultSet.getString(3) + "," + resultSet.getBlob(4) + ","
                    + resultSet.getString(5) + resultSet.getBlob(6) + ","
                    + resultSet.getString(11));
        }
    }

    class MyJDBC {
        public  void main(String[] args) throws ClassNotFoundException, SQLException {
            // 1 注册驱动
            Class.forName("org.postgresql.Driver");
            // 2 获取连接
            String url = "jdbc:postgresql://10.178.1.15:5432/zjmht_data";
            String username = "zjmht";
            String password = "zjmht";
            Connection connection = DriverManager.getConnection(url, username, password);

            // 3 获取sql语句执行对象
            String sql = "SELECT hcode,hname,type2 FROM public.bio_master_table\n" +
                    "ORDER BY id ASC LIMIT 100 ";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            // 4 执行并返回结果集
            ResultSet resultSet = preparedStatement.executeQuery();

            StringBuilder sb = new StringBuilder();
            while (resultSet.next()) {
                System.out.println(resultSet.getString(2) + ":" + resultSet.getString(1));
            }
            connection.close();
            System.out.println("resultSet = " + resultSet);

        }
    }

}
